<?php
/**
 * appRain v 0.1.x
 *
 * LICENSE
 *
 * This source file is subject to the MIT license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.opensource.org/licenses/mit-license.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@apprain.com so we can send you a copy immediately.
 *
 * @copyright  Copyright (c) 2010 appRain, Inc. (http://www.apprain.com)
 * @license    http://www.opensource.org/licenses/mit-license.php MIT license
 *
 * HELP
 *
 * Official Website
 * http://www.apprain.com/
 *
 * Download Link
 * http://www.apprain.com/download
 *
 * Documents Link
 * http ://www.apprain.com/documents
 */
class appstoreController extends appRain_Base_Core
{
    public $name = 'appStore';
    public $dispatch =  Array(  // Restrict Dispatch function
                                // for a specific method
                                'preDispatchExclude'=>array(),
                                'postDispatchExclude'=>array());

    /**
     * This function run before each
     * Action Method
     */
    public function __preDispatch()
    {
        $this->set("selected","store");
        $this->set("offRight",true);
    }

    /**
     * Render Store product display page
     * - URL are customize by
     *   URI_Manager >> Page_Router
     */
    public function indexAction($action=null, $id=null, $page=1)
    {
        // Set page meta information
        $this->staticPageNameToMetaInfo('Store');
        // Attach addons
        $this->addons = Array('appcart','dropdownmenu','glitter');
        if($action == 'bycat')
        {
            // Fetch Products information from
            // Information Set by Category
            $products = App::InformationSet('product')
                        ->setPagination('Yes')
                        ->setSmartPaging(true)
                        ->setPage($page)
                        ->setLimit(9)
                        ->setHLink(App::Helper('Config')->baseurl("/store-by-cat/{$id}/[page]/" . App::Helper('Utility')->Text2Normalize(App::CategorySet()->idToName($id))))
                        ->setNextCaption('Next >>')
                        ->setPrevCaption('<< Prev')
                        ->findAll(
                                    "1 ORDER BY id DESC",
                                    Array(
                                            Array("category"=>"%{$id}%",'cnd'=>'LIKE'),
                                            "AND",
                                            Array("status"=>"Active")
                                          )
                                 );
            $this->set('products',$products);

            $this->page_title = App::CategorySet()->idToName($id);
            $this->set("section_title",App::CategorySet()->idToName($id,'short'));
            $this->set("catid",$id);
        }
        else
        {
			$category = App::CategorySet('product-cat')->find('1 order by id desc');
			$this->redirect("/teddybearshopping");
			exit;

            // Fetch all Featured Products
            $page = is_numeric($action) ? $action : 1;
            $products = App::InformationSet('product')
                            ->setPagination('Yes')
                            ->setSmartPaging(true)
                            ->setPage($page)
                            ->setHLink(App::Helper('Config')->baseurl("/store"))
                            ->setLimit(9)
                            ->setNextCaption('Next >>')
                            ->setPrevCaption('<< Prev')
                            ->findAll("1 ORDER BY RAND()",Array(Array("status"=>"Active"),"AND",Array("isfeatured"=>"Yes")));
            $this->set('products',$products);

            $this->set("section_title","Featured Product");
            $this->set("catid","");
        }

        $this->set("action",$action);
    }

    /**
     * Function called by AJAX Request
     * Add/Update product to cart
     */
    public function add2qcartAction($pcid=null,$qty=null)
    {
        if(!isset($this->get['ajax']))$this->redirect('/');
        $this->layout = 'empty';

        try
        {
			$arr = explode('|',$pcid);
			$pid = $arr[0];
			$cid = $arr[1];

            App::Component('appStore')->Helper('Data')->quickAdd($pid,$qty);
            $totalitem = App::Component('appStore')->Helper('Data')->getCartTotalItem();

			$product = App::InformationSet()->findById($pid);

            echo App::Load("Module/Cryptography")->jsonEncode(
				array("_status" =>"Success",
					  "_location"=>$this->baseUrl("/store-by-product/{$pcid}"),
					  "_hastocheckout"=>App::Component('appStore')->Helper('Data')->isToCheckout(),"totalitem"=>$totalitem,"_message"=>$this->__('Cart updated successfully.')));

        }
        catch (AppException $e)
        {
            echo App::Load("Module/Cryptography")->jsonEncode(array( "_status" =>"Error", "_message"=>$e->getMessage()));
        }

    }

    /**
     * Render the checkout page
     */
    public function checkoutAction($action=null, $id=null)
    {
        // Set Meta information of the page
        $this->staticPageNameToMetaInfo('Checkout');
        // Attached all addons need for this section
        $this->addons = Array('datagrid','defaultvalues','validation','ajaxsubmit','appcheckout','tab');

        $cartinfo = App::Component('appStore')->Helper('Data')->getCartInfo();
        if(empty($cartinfo))
        {
            $this->redirect("/store");
            exit;
        }

        // Remove Items from cart
        if($action=='removeitem')
        {
            App::Component('appStore')->Helper('Data')->removeItem($id);
            $this->redirect("/checkout");
            exit;
        }

        $this->set("section_title","Checkout");
    }
    /**
     * Function called by ajax Request to
     * Complete the Checkout process
     */
    public function completeCheckoutAction()
    {
        $this->layout = 'empty';
        if(empty($this->data))
        {
            $this->redirect('/');
            exit;
        }

        try
        {
            if(isset($this->data['Checkout']['shiptobillingaddress']))
            {
               $this->data['Shipping'] =  $this->data['Billing'];
            }
            // This call complete the Checkout process and also
            // execute payment processor. We used some magic
            // Functions to show the strength of function calling
            // here.
            //
            // If any Function throw any Excepion from anywhere
            // then program control move in Catch Section with executing
            // rest part of the coding flow. This process
            // helps you to add as many payment processory you need
            // that controll the Checkout operation.
            // For help: www.apprain.com/ticket
            App::Component('appStore')->Helper('Data')
               // This is a magic method to set post data . Data can be
               // retrived by $this->getCheckoutPostData(). This function
               // return object of own class to mantain the chain of other call.
               ->setCheckoutPostData($this->data)
			   ->organiseResource()
			   ->orderValidation()
               // Start checkout Process and execute payment processor. This funtion throw
               // exception for any Invalid Result and stop all further execution
               ->StartCheckoutProcess()
               // Change the order status changed to PAID as no exception thrown from previouse
               // function.
               ->ChnageOrderStatus()
               // Clear cart SESSION.
               ->clearcart();

            // Return to Payment Success page
            echo App::Load("Module/Cryptography")->jsonEncode(array("_status" =>"Redirect","_location"=>$this->baseUrl("/payment-success")));
        }
        catch (AppException $e)
        {
            echo App::Load("Module/Cryptography")->jsonEncode(array( "_status" =>"Error", "_message"=>$e->getMessage()));
        }
    }

    /**
     * Display Order status pages
     */
    public function statusmessageAction($page_name=null)
    {
        if(!isset($page_name))
        {
            $this->redirect("/");
            exit;
        }

        // Clear Cart
        App::Component('appStore')->Helper('Data')->clearcart();

        $page_content = $this->staticPageNameToMetaInfo($page_name);
        $this->set( 'page_content' ,$page_content );
        $this->set("section_title","Simple Store");
        $this->set("selected","store");
    }

    /**
     * Manage Order data from admin panel
     */
    public function manageordersAction($action=NULL,$id=NULL)
    {
        $this->setAdminTab('catalog');

        if($action=='view')
        {
            if(!empty($this->data))
            {
                $this->data['Order']['id'] = $id;

                $obj = App::Model('Order')->Save($this->data);
                $this->redirect("/appstore/manageorders");
                exit;
            }

            $oderdata = App::Model('Order')->findById($id);

        }
        else
        {
            $this->addons = Array('row_manager');
            $oderdata = App::Model('Order')->Paging("1 ORDER BY ID DESC");
        }

        $this->set('action',$action);
        $this->set('oderdata',$oderdata);
    }

	public function productAction($action=null,$pcid=null)
	{
		$this->addons = Array('defaultvalues','personalized');
		$arr = explode('|',$pcid);
		$pid = $arr[0];
		$cid = $arr[1];

		if(!empty($this->data))
		{
			$iteminfo = App::Module('Session')->read('iteminfo');
			$iteminfo[$pid] = $this->data['Order']['data'];
			App::Module('Session')->Write('iteminfo',$iteminfo);
			$this->redirect("/checkout");
			exit;
		}

		$product = App::InformationSet()->findById($pid);

		$productArr = App::Component('AppStore')->Helper('Product')->getRelatedProduct($cid);
		$this->set('productArr',$productArr);

		$hoodieArr = App::Component('AppStore')->Helper('Product')->getRelatedHoodie($cid);
		$this->set('hoodieArr',$hoodieArr);

		$cardArr = App::Component('AppStore')->Helper('Product')->getRelatedCard($cid);
		$this->set('cardArr',$cardArr);

		$this->set('pid',$pid);
		$this->set('cid',$cid);
        $this->set('bearselected',$product);
	}




    # * --------------------------------------------------------------------------
    # *	      THIS SECTION FOR PAYPLA STANDARD
    # *	      You can move if needed.
    # *---------------------------------------------------------------------------

    /**
     * Post Paypal data
     */
    public function paypal_postAction()
    {
        $this->layout = 'empty';
        App::Component('appStore')->Helper("Pgateway_paypal")
           ->setAmount(App::Component('appStore')->Helper('Data')->totalCost())
           ->setOrderId(App::Component('appStore')->Helper('Data')->getOrderId())
           ->submitPost();
    }

    /**
     * Process IPN request
     */
    public function paypalipnAction()
    {
        $this->layout = 'empty';
        App::Component('appStore')->Helper("Pgateway_paypal")->ExecuteIPN();
    }
}
